import React, { Component } from 'react'
import Breadcrumb from '../base/Breadcrumb'
import { Input, Message } from 'element-react'
import {withRouter} from 'react-router-dom'

class memberGrowOperate extends Component {
  constructor (props) {
    super(props)
    this.state = {
      levelName: '',
      standardCondition: ''
    }
  }
  componentDidMount () {
    if (this.props.match.params.id) {
      let memberGrowItem = JSON.parse(window.sessionStorage.getItem('memberGrowItem'))
      this.setState({levelName: memberGrowItem.levelName, standardCondition: memberGrowItem.standardCondition})
    }
  }
  cancel () {
    this.props.history.goBack()
  }
  submit () {
    if (this.state.levelName === '' || this.state.standardCondition === '') {
      Message.error('请填入完整信息')
      return
    }
    if (this.props.match.params.id) {
      this.$ajax.editConsumerGrow({id: this.props.match.params.id, levelName: this.state.levelName, standardCondition: this.state.standardCondition}).then(res => {
        if (res.code === 200) {
          Message({
            type: 'success',
            message: '提交成功'
          })
          this.props.history.goBack()
        } else {
          Message.error('提交失败')
        }
      }).catch(() => {
        Message.error('网络错误')
      })
    } else {
      this.$ajax.addConsumerGrow({levelName: this.state.levelName, standardCondition: this.state.standardCondition}).then(res => {
        if (res.code === 200) {
          Message({
            type: 'success',
            message: '提交成功'
          })
          this.props.history.goBack()
        } else {
          Message.error('提交失败')
        }
      }).catch(() => {
        Message.error('网络错误')
      })
    }
  }
  render () {
    return (
      <div className="memberGrowOperate">
        {
          this.props.match.params.id ? <Breadcrumb data={['会员', '成长规则', '编辑']}/> : <Breadcrumb data={['会员', '成长规则', '新增']}/>
        }
        <div className="inputGroup">
          <label className="inputLabel">等级名称：</label>
          <Input placeholder="请输入等级名称" size="small" className="inputSmall" value={this.state.levelName} onChange={levelName => {this.setState({levelName})}}/>
        </div>
        <div className="inputGroup">
          <label className="inputLabel">达标条件（平台积分）：</label>
          <Input placeholder="请输入达标条件（平台积分）" size="small" className="inputSmall" value={this.state.standardCondition} onChange={standardCondition => {this.setState({standardCondition})}}/>
        </div>
        <button type="button" className="btn btn-cancel" onClick={this.cancel.bind(this)}>取消</button>
        <button type="button" className="btn btn-save" onClick={this.submit.bind(this)}>保存</button>
      </div>
    )
  }
}
export default withRouter(memberGrowOperate)